/**
 * @Title:  GroupPhotoActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-4-26 下午5:13:20 
 * @version:  V1.0 
 */

package artid.com.arttogoa.keeponrecord;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import artid.com.arttogoa.BaseActivity;
import artid.com.arttogoa.HomeActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.glide.GlideUtil;
import artid.com.arttogoa.parser.ArtworkImageUpload;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.VioceUtils;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2016-4-26 下午5:13:20
 * @version: V1.0
 */
public class GroupPhotoActivity extends BaseActivity implements OnClickListener {
	private Button complete;
	private LinearLayout plus;
	private RelativeLayout im_rel;
	private AlertDialog alertDialog;
	private ImageView graphImage;
	private EditText info;
	private ImageView vioce;
	private VioceUtils vu;
	private String userPhone;
	private String Type;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_photo);
		ArtWorkApp.getInstance().addArtActivity(GroupPhotoActivity.this);
		System.out.println("token=" + AppUtil.getUser().getToken());
		setContent(GroupPhotoActivity.this, getIntent());
		complete = (Button) findViewById(R.id.btn_complete);
		plus = (LinearLayout) findViewById(R.id.ll_plus);
		im_rel = (RelativeLayout) findViewById(R.id.im_rel);
		info = (EditText) findViewById(R.id.ed_info);
		graphImage = (ImageView) findViewById(R.id.iv_photo_graph);
		vioce = (ImageView) findViewById(R.id.iv_vioce);
		/** 初始化备案模式 **/
		vu = new VioceUtils(GroupPhotoActivity.this, vioce, info);
		vu.init();
		complete.setOnClickListener(this);
		graphImage.setOnClickListener(this);
		im_rel.setOnClickListener(this);
		plus.setOnClickListener(this);
		mBack.setOnClickListener(this);
		// vioce.setOnClickListener(this);
		mTittle.setText("合影");
		/** 初始化标题标志 **/
		Type = MySharedPreferences.getMySharedPreferences(
				GroupPhotoActivity.this).getValue(Cache.ART_TYPE, "");
		Drawable drawable = null;
		if (Type.equals(ArtRecordActivity._PHONE)) {
			drawable = getResources().getDrawable(R.drawable.a_ico_iphone);
		} else if (Type.equals(ArtRecordActivity._FILING)) {
			drawable = getResources().getDrawable(R.drawable.a_ico_shebei);
		}
		// / 这一步必须要做,否则不会显示.
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		mTittle.setCompoundDrawablePadding(20);
		mTittle.setCompoundDrawables(drawable, null, null, null);

		userPhone = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue("Phone", "");

		initCache();
		registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
		// AlertUtils.initUploadAlertDialog(GroupPhotoActivity.this,
		// GroupPhotoActivity.this.getWindowManager()
		// .getDefaultDisplay().getWidth(), "正在上传合影及完整图");
	}

	/**
	 * 监听是否点击了home键将客户端推到后台
	 */
	private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
		String SYSTEM_REASON = "reason";
		String SYSTEM_HOME_KEY = "homekey";
		String SYSTEM_HOME_KEY_LONG = "recentapps";

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { 
				String reason = intent.getStringExtra(SYSTEM_REASON);
				if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
					// 表示按了home键,程序到了后台 
					storageCache();
				} else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
					// 表示长按home键,显示最近使用的程序列表
					storageCache();
				}
			}
		}
	};

	void storageCache() {
		MySharedPreferences.getMySharedPreferences(GroupPhotoActivity.this)
				.setValue(Cache.IS_CACHE + userPhone, "true");
		String cache = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.ART_CACHE + userPhone, "");
		try {
			JSONObject ob;
			if (TextUtils.isEmpty(cache)) {
				ob = new JSONObject();
			} else {
				ob = new JSONObject(cache);
			}
			String infoString = info.getText().toString().trim();
			if (!TextUtils.isEmpty(infoString)) {
				ob.put("gphoto_detail", infoString);
			}
			if (!TextUtils.isEmpty(imageUrl)) {
				ob.put("gphotodata", imageUrl);
			}
			ob.put("updataType", Type);
			if (!TextUtils.isEmpty(infoString) || !TextUtils.isEmpty(imageUrl))
				MySharedPreferences.getMySharedPreferences(mContext).setValue(
						Cache.ART_CACHE + userPhone, ob.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		storageCache();
		super.onDestroy();
	}

	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	//
	// if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	// // do something...
	// storageCache();
	// finish();
	// return true;
	// }
	// return super.onKeyDown(keyCode, event);
	// }

	void initCache() {

		String cacheBo = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue(Cache.IS_CACHE + userPhone, "false");
		System.out.println(cacheBo);
		System.out.println(Cache.IS_CACHE + userPhone);
		if (Boolean.valueOf(cacheBo)) {
			String cache = MySharedPreferences.getMySharedPreferences(mContext)
					.getValue(Cache.ART_CACHE + userPhone, "");
			System.out.println("cache=" + cache);
			try {
				JSONObject ob = new JSONObject(cache);
				String gphoto_detail = ob.optString("gphoto_detail");
				if (!TextUtils.isEmpty(gphoto_detail)) {
					info.setText(gphoto_detail);
				}
				String gphotodata = ob.optString("gphotodata");
				if (!TextUtils.isEmpty(gphotodata)) {
					imageUrl = gphotodata;
					GlideUtil.setImage1(mContext, gphotodata,
							R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
							graphImage);
					plus.setVisibility(View.GONE);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.btn_complete:
			String infoString = info.getText().toString();
			// if (TextUtils.isEmpty(infoString)) {
			// Toast.makeText(mContext, "描述不能为空~", 2).show();
			// return;
			// }
			// else
			if (TextUtils.isEmpty(imageUrl)) {
				Toast.makeText(mContext, "请选择合影图~", 2).show();
				return;
			}
			ArtworkImageUpload artwork = new ArtworkImageUpload();
			// System.out.println(imageUrl);
			artwork.setGphotodata(imageUrl);
			artwork.setGphoto_detail(TextUtils.isEmpty(infoString) ? ""
					: infoString);
			DataKeeper.keepSerializable(mContext, artwork);
			storageCache();
			Intent intent = new Intent(GroupPhotoActivity.this,
					UploadCompleteGraphActivity.class);
			startActivity(intent);
			break;
		case R.id.back_btn:
			finish();
			break;
		// case R.id.iv_vioce:
		//
		// break;
		case R.id.iv_photo_graph:
			alertDialog = AlertUtils.initPhotoAlertDialog(
					GroupPhotoActivity.this, GroupPhotoActivity.this
							.getWindowManager().getDefaultDisplay().getWidth(),
					new OnClickListener() {
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							switch (view.getId()) {
							case R.id.tv_phone:
								CameraUtils
										.openCameraImage(GroupPhotoActivity.this);
								// Intent intentMe = new Intent(
								// MediaStore.ACTION_IMAGE_CAPTURE);
								// startActivityForResult(intentMe, 1);

								alertDialog.dismiss();
								break;
							case R.id.tv_choice:
								Intent intent = new Intent(
										GroupPhotoActivity.this,
										HomeActivity.class);
								intent.putExtra("type", Cache.T_GP);
								startActivityForResult(intent, 2);
								alertDialog.dismiss();
								break;
							default:
								break;
							}
						}
					});
			break;

		default:
			break;
		}
	}

	String imageUrl = "";

	@SuppressLint("SdCardPath")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			String path = BitmapUtil.getRealFilePath(mContext, uri);
			// String sdStatus = Environment.getExternalStorageState();
			// if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			// Log.i("TestFile",
			// "SD card is not avaiable/writeable right now.");
			// return;
			// }
			// @SuppressWarnings("static-access")
			// String name = new DateFormat().format("yyyyMMdd_hhmmss",
			// Calendar.getInstance(Locale.CHINA))
			// + ".jpg";
			// // Toast.makeText(this, name, Toast.LENGTH_LONG).show();
			// Bundle bundle = data.getExtras();
			// Bitmap bitmap = (Bitmap) bundle.get("data");//
			// 获取相机返回的数据，并转换为Bitmap图片格式
			//
			// FileOutputStream b = null;
			// // ???????????????????????????????为什么不能直接保存在系统相册位置呢？？？？？？？？？？？？
			// File file = new File("/sdcard/myImage/");
			// file.mkdirs();// 创建文件夹
			// String fileName = "/sdcard/myImage/" + name;
			// imageUrl = fileName;
			// try {
			// b = new FileOutputStream(fileName);
			// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			// } catch (FileNotFoundException e) {
			// e.printStackTrace();
			// } finally {
			// try {
			// b.flush();
			// b.close();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
			// }
			// graphImage.setImageBitmap(b);// 将图片显示在ImageView里
			imageUrl = path;
			GlideUtil.setImage1(mContext, path, R.drawable.yspba_img_mor,
					R.drawable.yspba_img_mor, graphImage);
			plus.setVisibility(View.GONE);
			// Glide.with(mContext).load(new File(path))
			// .placeholder(R.drawable.yspba_img_mor)
			// .error(R.drawable.yspba_img_mor).into(graphImage);
		} else if (requestCode == 2 && resultCode == 3) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			// Bitmap bitmap = getLoacalBitmap(fb.getImgURL()); // 从本地取图片
			// graphImage.setImageBitmap(bitmap);
			imageUrl = fb.getImgURL();
			GlideUtil.setImage1(mContext, fb.getImgURL(),
					R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
					graphImage);
			plus.setVisibility(View.GONE);
			// Glide.with(mContext).load(new File(fb.getImgURL())).fitCenter()
			// .placeholder(R.drawable.yspba_img_mor)
			// .error(R.drawable.yspba_img_mor).into(graphImage);
			// info.setText("图片名称：" + fb.getName() + "\n图片大小:" +
			// fb.getFileSize());
		} else if (requestCode == 2 && resultCode == 4) {
			Bundle bundle = data.getExtras();
			FilesBean fb = (FilesBean) bundle.getSerializable("image");
			System.out.println(fb.getThumbURL());
			// Bitmap bitmap = getLoacalBitmap(fb.getThumbURL()); // 从本地取图片
			// graphImage.setImageBitmap(bitmap);
			imageUrl = fb.getThumbURL();
			GlideUtil.setImage1(mContext, fb.getThumbURL(),
					R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
					graphImage);
			plus.setVisibility(View.GONE);
			// Glide.with(mContext).load(new File(fb.getThumbURL())).fitCenter()
			// .placeholder(R.drawable.yspba_img_mor)
			// .error(R.drawable.yspba_img_mor).into(graphImage);
			// info.setText("图片名称：" + fb.getName() + "\n图片大小:" +
			// fb.getFileSize());
		}

		System.out.println("imageUrl===" + imageUrl);
	}

	/**
	 * 加载本地图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getLoacalBitmap(String url) {
		imageUrl = url;
		try {
			FileInputStream fis = new FileInputStream(url);
			Bitmap bitmap = BitmapFactory.decodeStream(fis);
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
}
